小编Zef*_*ndo的帖子

Flutter:处理错误 Dio 包(404,400 等)

我正在学习使用包DIO https://pub.dev/packages/dio通过 ID 搜索数据,我的问题是每次输入错误的关键字搜索时,应用程序突然崩溃并显示调试消息404 Not Found

在此处输入图片说明

我知道找不到数据,因为我输入了错误的关键字,但我已经用这段代码处理了这个问题

Widget _searchKeywordMahasiswa() {
    return FutureBuilder<List<Mosque>>(
      future: api.getMahasiswaById(_searchText),
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        if (snapshot.hasData) {
          return Expanded(
            child: ListView.builder(
              shrinkWrap: true,
              itemCount: snapshot.data.length,
              itemBuilder: (BuildContext context, int index) {
                return Text(snapshot.data[index].id);
              },
            ),
          );
        } else if (!snapshot.data) { <<<<<< IN THIS LINE
          return Center(
            child: Icon(
              Icons.sentiment_very_dissatisfied,
              size: 150.0,
            ),
          );
        }
        return CircularProgressIndicator();
      },
    );
    // return CircularProgressIndicator();
  }
Run Code Online (Sandbox Code Playgroud)
Future<List<Mosque>> getMahasiswaById(String id) async{
    try {
      var …
Run Code Online (Sandbox Code Playgroud)

dart flutter

18
推荐指数
5
解决办法
4万
查看次数

Flutter:依赖与 dev_dependencies

在此处输入图片说明 我想知道依赖项dev_dependencies之间的区别

当我将包放入依赖项/ dev_dependencies

是什么把package放在dependencies / dev_dependencies中,让APK的大小变大?(我还没有尝试发布 apk 来查看不同的大小)

因为我在 Visual Studio 代码Pubspec Assist 中使用了扩展,所以这个扩展会自动向pubspec.yaml添加依赖

谢谢

dart flutter

15
推荐指数
2
解决办法
3969
查看次数

Flutter:如何将 Future&lt;String&gt; 转换为 String?

我使用 API 从数据库中获取图像。我有这样的回应:

{
    "status": "ok",
    "message": "Logo Client Is Found",
    "data": [
        {
            "fileInfo": "img-1.png"
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

我想使用以下代码从 API 获取该值:

 Future<String> getLogoClient() async {
    final response = await _client.get("$_baseUrl/getLogoClient");
    final Map<String, dynamic> responseJson = json.decode(response.body);
    if (responseJson["status"] == "ok") {
      List image = responseJson["data"];
      final imageList =
          image.map((json) => AppInfoModel.logoFromJson(json)).toList();
      final singleImage = imageList.single.fileInfo;
      final String urlImage = "$baseImageUrl/$singleImage";
      print(urlImage);
      return urlImage;
    } else {
      throw CustomError(responseJson["message"]);
    }
  }
Run Code Online (Sandbox Code Playgroud)

打印响应:

http://---/images/info/img-1.png
Run Code Online (Sandbox Code Playgroud)

问题是,我想将值从 Future 转换为 String我该怎么做?

我已经尝试使用此代码并成功转换该值: …

api dart flutter

15
推荐指数
2
解决办法
3万
查看次数

Flutter Dio:如何上传图片?

我正在尝试邮递员。它有效

邮差 我想使用 Package DIO Package将一些图像上传到 rest-api ,我是这个包的新手(我将此包仅用于 CRUD 操作),并且在上传图像操作时遇到问题。
我已经在阅读文档,但没有看到上传图片。我正在尝试此代码(参考文档)并遇到一些错误:

error:FileSystemException
message :"Cannot retrieve length of file"
OSError (OS Error: No such file or directory, errno = 2)
"File: '/storage/emulated/0/Android/data/com.example.mosque/files/Pictures/scaled_IMG_20190815_183541.jpg'"
Type (FileSystemException)
message:FileSystemException: Cannot retrieve length of file, path = 'File: '/storage/emulated/0/Android/data/com.example.mosque/files/Pictures/scaled_IMG_20190815_183541.jpg'' (OS Error: No such file or directory, errno = 2)
DioErrorType (DioErrorType.DEFAULT)
name:"DioErrorType.DEFAULT"
Run Code Online (Sandbox Code Playgroud)

飞镖

Future uploadImage({dynamic data,Options options}) async{
      Response apiRespon =  await dio.post('$baseURL/mahasiswa/upload/',data: data,options: options);
      if(apiRespon.statusCode== 201){
        return apiRespon.statusCode==201;
      }else{
        print('errr');
        return null;
      }
}
Run Code Online (Sandbox Code Playgroud)

查看.dart …

dart flutter dio

13
推荐指数
4
解决办法
3万
查看次数

实施 ChangeNotifier 与 StateNotifier

我非常熟悉Provider包并将其与ChangeNotifier.

假设我有 3 个 getter 和具有不同功能的方法:

  1. 切换加载
  2. 切换图像加载
  3. 切换 ObsecurePassword

使用 ChangeNotifer

import 'package:flutter/foundation.dart';

class GlobalChangeNotifier extends ChangeNotifier {
  bool _isLoading = false;
  bool _isImageLoading = false;
  bool _isObsecurePassword = false;

  bool get isLoading => _isLoading;
  bool get isImageLoading => _isImageLoading;
  bool get isObsecurePassword => _isObsecurePassword;

  void setLoading(bool value) {
    _isLoading = value;
    notifyListeners();
  }

  void setImageLoading(bool value) {
    _isImageLoading = value;
    notifyListeners();
  }

  void setObsecurePassword(bool value) {
    _isObsecurePassword = !value;
    notifyListeners();
  }
}

final globalChangeNotifier …
Run Code Online (Sandbox Code Playgroud)

flutter riverpod

13
推荐指数
1
解决办法
5351
查看次数

Flutter 本地通知图标不显示

我有一个使用Package Flutter Local notification来显示通知的应用程序。一切都很好,我可以显示通知。问题是我的图像,因为图标通知不显示,仅显示图像的全彩。

我做了什么:

  • 像文档一样设置 InitLocalNotification

    void initLocalNotification() async {
        _androidInitializationSettings = AndroidInitializationSettings('app_icon');
        _iosInitializationSettings = IOSInitializationSettings(
          onDidReceiveLocalNotification: _onDidReceiveLocalNotification,
        );
    
        _initializationSettings = InitializationSettings(
          _androidInitializationSettings,
          _iosInitializationSettings,
        );
    
        await _flutterLocalNotificationsPlugin.initialize(
          _initializationSettings,
          onSelectNotification: _onSelectNotification,
        );
      }
    
    Run Code Online (Sandbox Code Playgroud)
  • 像文档一样设置结构文件夹

  • 调整我的徽标大小,如文档中的徽标(宽度:36px,高度:36px,背景:透明,扩展名:.png)

    在此输入图像描述

尽管我已经完成了上述方法,但我的图像图标没有显示,只显示颜色。

结果(不起作用)

之后,我尝试使用文档中的图像更改我的图像,并且这是有效的。图像图标显示在通知中。

图片来自文档

在此输入图像描述

结果(有效)

我错过了什么吗?

notifications flutter

9
推荐指数
1
解决办法
2万
查看次数

Flutter : "Could not resolved the package" every install new packages

I have some problem about installing new package from pub.dev. I create my own package inside my root project with this command :

flutter create --template=package main_template

structure folder

结构文件夹

I installing new package inside main_template not lib. every install new package in main_template i received this error :


Compiler message:
Error: Could not resolve the package 'device_info' in 'package:device_info/device_info.dart'.
sinergi_flutter_template/main_template/lib/variable/get_device_id.dart:3:8: Error: Not found: 'package:device_info/device_info.dart'
import 'package:device_info/device_info.dart';
       ^
sinergi_flutter_template/main_template/lib/variable/get_device_id.dart:9:11: Error: 'DeviceInfoPlugin' isn't a type.
    final DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin();
          ^^^^^^^^^^^^^^^^ …
Run Code Online (Sandbox Code Playgroud)

dart flutter

8
推荐指数
3
解决办法
1万
查看次数

Flutter:生成唯一整数 ID 本地通知

在此输入图像描述

我有这样的情况,当用户按下按钮时我应该显示 2 个不同的时间表通知。但问题是两个通知具有相同的 ID,这将使旧通知将替换为新通知。因此,我采用另一种方法来使用DateTime().now.millisecondSinceEpoch生成唯一 ID 。
这种方法的另一个问题是,我收到错误 max length INTEGER Unhandled Exception: Invalid argument (id): must fit within the size of a 32-bit integer i.e. in the range [-2^31, 2^31 - 1]:
如何为不同的通知创建唯一的INTEGER id?

1599943560000 是我从 DateTime 到 millisecondSinceEpoch 的转换

通知源代码


  Future<void> scheduleNotification({
    @required DateTime dateTimeShowNotification,
    @required int idNotification,
    String titleNotification = 'default title',
    String bodyNotification = 'default body',
    String payloadNotification = 'payload schedule notification',
  }) async {
    var androidChannelSpecifics = AndroidNotificationDetails(
      'CHANNEL_ID 2',
      'CHANNEL_NAME 2', …
Run Code Online (Sandbox Code Playgroud)

flutter

8
推荐指数
1
解决办法
2327
查看次数

Flutter : local_auth: ^0.6.1 : PlatformException(error, You need to use a Theme.AppCompat theme (or后代) with this Activity., null)

我在使用包Local Auth集成我的应用程序时遇到问题,我已经按照有关配置包到我的应用程序的文档进行操作。在文档中它说:

请注意,local_auth插件需要使用 FragmentActivity 而不是 Activity。这可以通过切换到在清单中使用 FlutterFragmentActivity 而不是 FlutterActivity 来轻松完成(如果您要扩展基类,则使用您自己的 Activity 类)。

但是在我编辑MainActivity.kt后问题出现了 :

package id.zeffry.debt_diary

import androidx.annotation.NonNull;
import io.flutter.embedding.android.FlutterFragmentActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugins.GeneratedPluginRegistrant

import android.os.Build
import android.view.ViewTreeObserver
import android.view.WindowManager
class MainActivity: FlutterFragmentActivity() {
    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
        GeneratedPluginRegistrant.registerWith(flutterEngine);
    }
}
Run Code Online (Sandbox Code Playgroud)

日志

I/flutter (22608): PlatformException(error, You need to use a Theme.AppCompat theme (or descendant) with this activity., null)
Run Code Online (Sandbox Code Playgroud)

来自文档的源代码:

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:local_auth/local_auth.dart';

//? Testing Local Auth( Finger …
Run Code Online (Sandbox Code Playgroud)

dart flutter

7
推荐指数
2
解决办法
2454
查看次数

Flutter:防止 FutureBuilder 总是刷新每个更改屏幕

我有 FutureBuilder 从 API 和代码中获取用户资料来获取用户,如下所示:

 Future<List<UserModel>> getUserByUsername({@required String username}) async {
    try {
      final response =
          await _client.get("$_baseUrl/getUserByUsername?username=$username");
      final Map<String, dynamic> responseJson = json.decode(response.body);
      if (responseJson["status"] == "ok") {
        List userList = responseJson['data'];
        final result = userList
            .map<UserModel>((json) => UserModel.fromJson(json))
            .toList();
        return result;
      } else {
        throw CustomError(responseJson['message']);
      }
    } catch (e) {
      return Future.error(e.toString());
    }
  }
Run Code Online (Sandbox Code Playgroud)

未来的建设者

如果您在上面的 GIF 中可以看到,My FutureBuilder 位于 BottomNavigationBar 内。每次我从 BottomNavigationBar 更改屏幕/页面并回到我的 FutureBuilder 总是刷新!

我如何才能将其修复为仅刷新一次?

主屏幕

class _HomeScreenState extends State<HomeScreen> {
  @override
  Widget build(BuildContext context) { …
Run Code Online (Sandbox Code Playgroud)

dart flutter

6
推荐指数
2
解决办法
3852
查看次数

标签 统计

flutter ×10

dart ×7

api ×1

dio ×1

notifications ×1

riverpod ×1