繁体   English   中英

ValueListenableBuilder 没有重建屏幕,在热重载时,它正在工作

[英]ValueListenableBuilder is not rebuilding the screen, when hotreloading, it is working

我正在尝试构建一个笔记应用程序,所有数据和其他东西都运行良好,因为在保存代码文件时数据显示在屏幕上,这很奇怪,第一次遇到这个问题

简而言之,当从应用程序添加数据时,valuelistanble 不在监听,而是在热重载数据时显示

我该如何解决这个问题,这是代码

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    WidgetsBinding.instance!.addPostFrameCallback((_) async {
      final value = await NoteDB.instance.getAllNotes();
    });

           ____________________________________________
           ____________________________________________
           //code line for aligment 

            Expanded(
                child: ValueListenableBuilder(
              valueListenable: NoteDB.instance.noteListNotifier,
              builder: (context, List<NoteModel> newNotes, _) {
                return GridView.count(
                  childAspectRatio: 3 / 4,
                  crossAxisCount: 2,
                  mainAxisSpacing: 34,
                  crossAxisSpacing: 30,
                  padding: const EdgeInsets.all(20),
                  //generating list for all note
                  children: List.generate(
                    newNotes.length,
                    (index) {
                      //setting the notelist to a variable called [note]
                      final note = newNotes[index];
                      if (note.id == null) {
                        //if the note's id is null set to sizedbox
                        //the note id never be null
                        const SizedBox();
                      }
                      return NoteItem(
                        id: note.id!,
                        //the ?? is the statement (if null)
                        content: note.content ?? 'No Content',
                        title: note.title ?? 'No Title',
                      );
                    },
                  ),
                );
              },
            )),

这是 NoteDB.instance.getAllNotes(); function

       @override
  Future<List<NoteModel>> getAllNotes() async {
  

    final _result = await dio.get(url.baseUrl+url.getAllNotes);
    if (_result.data != null) {
      final  noteResponse = GetAllNotes.fromJson(_result.data);
      noteListNotifier.value.clear();
      noteListNotifier.value.addAll(noteResponse.data.reversed);
      noteListNotifier.notifyListeners();
      return noteResponse.data;
    } else {
      noteListNotifier.value.clear();
      return [];
    }

  }

还有一个创建笔记的页面,当按下创建笔记按钮时,只有一个 function 在这里调用是 function

Future<void> saveNote() async {
    final title = titleController.text;
    final content = contentController.text;
    final _newNote = NoteModel.create(
      id: DateTime.now().millisecondsSinceEpoch.toString(),
      title: title,
      content: content,
    );
    final newNote = await NoteDB().createNote(_newNote);
    if (newNote != null) {
      print('Data Added to the DataBase Succesfully!');
      Navigator.of(scaffoldKey.currentContext!).pushAndRemoveUntil(
              MaterialPageRoute(
                  builder: (context) => HomePage()),
              (Route<dynamic> route) => false);
    } else {
      print('Error caught while data adding to the DataBase');
    }
  }

一切正常,但在添加数据时,即使通知程序处于活动状态,用户界面也不会刷新

如果您需要完整代码,请查看此 github 链接: https://github.com/Mishalhaneef/Note-app

由于此ValueNotifier的类型为List<NoteModel> ,因此当您将新项目添加到列表或从中删除或全部清除时,该值不会更改。 此处的值是对不会更改的列表的引用。

您必须为其分配一个新值,例如:

noteListNotifier.value = List<NoteModel>[<add your current items here>];

您可以使用List.fromremoveWhereadd等操作当前列表,然后重新分配完整列表。

此外,如果出现ValueNotifier ,您无需调用notifyListeners ,框架会处理它,请参见此处

另一种方法是使用自定义ChangeNotifierProvider ,您可以在列表内容更改时调用notifyListeners

一些进一步的建议:

  1. 在您的homescreen.dart文件中,您可以使用newNotes[index] NoteDB.instance.noteListNotifier.value[index]

  2. data.dart中,在getAllNotes中,您必须为noteListNotifier设置一个新值,以便传播更改。 目前您只是修改此列表中的项目,这不被视为更改。 试试这个代码:

  @override
  Future<List<NoteModel>> getAllNotes() async {
    //patching all data from local server using the url from [Post Man]
    final _result = await dio.get(url.baseUrl+url.getAllNotes);
    if (_result.data != null) {
      //if the result data is not null the rest operation will be operate
      //recived data's data decoding to json map
      final _resultAsJsonMap = jsonDecode(_result.data);
      //and that map converting to dart class and storing to another variable
      final getNoteResponse = GetAllNotes.fromJson(_resultAsJsonMap);
      noteListNotifier.value = getNoteResponse.data.reversed;
      //and returning the class
      return getNoteResponse.data;
    } else {
      noteListNotifier.value = <NoteModel>[];
      return [];
    }
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM