在FutureBuilder中设置提供者的价值

Cip*_*ian 6 dart flutter

我有一个小部件,它向返回地图的api发出请求。我想做的是每次加载小部件并将列表保存到appState.myList时都不会发出相同的请求,但是当我在中执行此操作时appState.myList = snapshot.data;FutureBuilder出现以下错误:

flutter: ??? EXCEPTION CAUGHT BY FOUNDATION LIBRARY ????????????????????????????????????????????????????????? flutter: The following assertion was thrown while dispatching notifications for MySchedule: flutter: setState() or markNeedsBuild() called during build. flutter: This ChangeNotifierProvider<MySchedule> widget cannot be marked as needing to build because the flutter: framework is already in the process of building widgets. A widget can be marked as needing to be flutter: built during the build phase only if one of its ancestors is currently building. ...

sun.dart文件

class Sun extends StatelessWidget {
  Widget build(BuildContext context) {
    final appState = Provider.of<MySchedule>(context);
    var db = PostDB();

    Widget listBuild(appState) {
      final list = appState.myList;
      return ListView.builder(
        itemCount: list.length,
        itemBuilder: (context, index) {
          return ListTile(title: Text(list[index].title));
        },
      );
    }

    Widget futureBuild(appState) {
      return FutureBuilder(
        future: db.getPosts(),
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.hasData) {
            // appState.myList = snapshot.data;
            return ListView.builder(
              itemCount: snapshot.data.length,
              itemBuilder: (context, index) {
                return ListTile(title: Text(snapshot.data[index].title));
              },
            );
          } else if (snapshot.hasError) {
            return Text("${snapshot.error}");
          }
          return Center(
            child: CircularProgressIndicator(),
          );
        },
      );
    }

    return Scaffold(
        body: appState.myList != null
            ? listBuild(appState)
            : futureBuild(appState));
  }
}
Run Code Online (Sandbox Code Playgroud)

postService.dart文件

class PostDB {
  var isLoading = false;

  Future<List<Postmodel>> getPosts() async {
    isLoading = true;
    final response =
        await http.get("https://jsonplaceholder.typicode.com/posts");

    if (response.statusCode == 200) {
      isLoading = false;
      return (json.decode(response.body) as List)
          .map((data) => Postmodel.fromJson(data))
          .toList();
    } else {
      throw Exception('Failed to load posts');
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我知道这些myList电话notifyListeners()是导致错误的原因。希望我说对了。如果是这样,如何appState.myList在应用中设置和使用而不会出现上述错误?

import 'package:flutter/foundation.dart';
import 'package:myflutter/models/post-model.dart';

class MySchedule with ChangeNotifier {
  List<Postmodel> _myList;

  List<Postmodel> get myList => _myList;

  set myList(List<Postmodel> newValue) {
    _myList = newValue;
    notifyListeners();
  }
}
Run Code Online (Sandbox Code Playgroud)

Rém*_*let 11

出现该异常是因为您正在同步修改来自其后代的小部件。

这很糟糕,因为它可能导致不一致的小部件树。一些小部件。可以使用突变前的值构建小部件,而其他人可能使用突变的值。

解决方案是消除不一致。使用ChangeNotifierProvider,通常有两种情况:

  • 您进行的突变ChangeNotifier也都一样内完成建造比创建了一个ChangeNotifier

    在这种情况下,您可以直接从您的构造函数进行调用ChangeNotifier

    class MyNotifier with ChangeNotifier {
      MyNotifier() {
        // TODO: start some request
      }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 执行的更改可能会“延迟”发生(通常在更改页面之后)。

    在这种情况下,您应该将您的突变包装在 anaddPostFrameCallback或 a 中Future.microtask

    class Example extends StatefulWidget {
      @override
      _ExampleState createState() => _ExampleState();
    }
    
    class _ExampleState extends State<Example> {
      MyNotifier notifier;
    
      @override
      void didChangeDependencies() {
        super.didChangeDependencies();
        final notifier = Provider.of<MyNotifier>(context);
    
        if (this.notifier != notifier) {
          this.notifier = notifier;
          Future.microtask(() => notifier.doSomeHttpCall());
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return Container();
      }
    }
    
    Run Code Online (Sandbox Code Playgroud)