1

我不明白为什么这里不接受提供者。

我的 main.dart 看起来像这样。

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: ChangeNotifierProvider<ContentDS>(
        builder: (_) => ContentDS(),
        child: Content(),
      )
    );
  }
}

Provider 在 Content Class 中完美运行。现在我使用此代码从内容移动到内容详细信息

Navigator.of(ctx).push(MaterialPageRoute(
                builder: (context) =>
                    ContentDetails(viewedList: listElement),
              ))

在内容详细信息中,我只是想再次访问提供者

 final ds = Provider.of<ContentDS>(context);

但这给了我以下错误

错误:在此 ContentDetails 小部件上方找不到正确的提供程序

要修复,请:

  • 确保 Provider 是此 ContentDetails 小部件的祖先 * 向 Provider 提供类型 * 向 Consumer 提供类型 * 向 Provider.of() 提供类型 * 始终使用包导入。例如:import 'package:my_app/my_code.dart'; * Ensure the correct上下文`正在被使用。

内容详细信息代码

class ContentDetails extends StatefulWidget {
  ToDoList viewedList;

  ContentDetails({this.viewedList});

  @override
  _ContentDetailsState createState() => _ContentDetailsState();
}

class _ContentDetailsState extends State<ContentDetails> with SingleTickerProviderStateMixin{

  bool isOpened = false;
  AnimationController _animationController;
  Animation<Color> _buttonColor;
  Animation<double> _animateIcon;
  Animation<double> _translateButton;
  Curve _curve = Curves.easeOut;
  double _fabHeight = 56.0;

  initState() {
    _animationController =
    AnimationController(vsync: this, duration: Duration(milliseconds: 500))
      ..addListener(() {
        setState(() {});
      });
    _animateIcon =
        Tween<double>(begin: 0.0, end: 1.0).animate(_animationController);
    _buttonColor = ColorTween(
      begin: Colors.blue,
      end: Colors.red,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: Interval(
        0.00,
        1.00,
        curve: Curves.linear,
      ),
    ));
    _translateButton = Tween<double>(
      begin: _fabHeight,
      end: -14.0,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: Interval(
        0.0,
        0.75,
        curve: _curve,
      ),
    ));
    super.initState();
  }

  @override
  dispose() {
    _animationController.dispose();
    super.dispose();
  }

  animate() {
    if (!isOpened) {
      _animationController.forward();
    } else {
      _animationController.reverse();
    }
    isOpened = !isOpened;
  }

  @override
  Widget build(BuildContext context) {
    final ds = Provider.of<ContentDS>(context);

    print(" ds.count ---> " + ds.count.toString());
    if (widget.viewedList != null){
      debugPrint(" widget.viewedList.primaryID ---> " + widget.viewedList.primaryID);
    }else{
      debugPrint(" It is null");
    }
    return
     Hero(
        tag: (widget.viewedList != null) ? widget.viewedList.primaryID : 'Hero',
        child: Scaffold(
          appBar: new AppBar(
            backgroundColor: ListStatusHelper.getBgGenericColor(widget.viewedList?.status ?? ListStatus.NONE),
            title: Text('${getListTitle()}'),
            elevation: 0.0,
          ),
          floatingActionButton:  Wrap(
            direction: Axis.vertical,
            children: <Widget>[
              transformWorks(edit(), 3),
              transformWorks(save(), 2),
              transformWorks(inbox(),1),
              toggleButton()
            ],
          ),
          body: Container(
              color: ListStatusHelper.getBgGenericColor(widget.viewedList?.status ?? ListStatus.NONE),
              child: const Text("Once Provider is available, need to work on this section");

            ),
          ),
    );
  }

  Widget transformWorks(Widget btn, int pos){
    return Transform(
      transform: Matrix4.translationValues(
        0.0,
        _translateButton.value * pos,
        0.0,
      ),
      child: btn,
    );
  }

  Widget inbox() {
    return Container(
      child: FloatingActionButton(
        heroTag: null,
        onPressed: null,
        tooltip: 'Inbox',
        elevation: 0.0,
        child: Icon(Icons.inbox),
      ),
    );
  }

  Widget edit() {
    return Container(
      child: FloatingActionButton(
        heroTag: null,
        onPressed: null,
        tooltip: 'Edit',
        elevation: 0.0,
        child: Icon(Icons.edit),
      ),
    );
  }

  Widget save() {
    return Container(
      child: FloatingActionButton(
        heroTag: null,
        onPressed: null,
        tooltip: 'Save',
        elevation: 0.0,
        child: Icon(Icons.save),
      ),
    );
  }

  Widget toggleButton(){
    return  FloatingActionButton(
      heroTag: null,
      backgroundColor: _buttonColor.value,
      onPressed: animate,
      tooltip: 'Toggle',

      child: AnimatedIcon(
        icon: AnimatedIcons.menu_close,
        progress: _animateIcon,
      ),
    );
  }

  String getListTitle() {
    if (widget.viewedList != null) {
      return widget.viewedList.listTitle;
    } else {
      return 'New List';
    }
  }
}

我是一名正在尝试学习 Flutter 的 iOS 开发人员,我认为 Provider 应该可用于属于导航流的所有类,而无需使用任何 DI。

帮助我意识到我错过了什么。在上述情况下的导航流的情况下应该如何使用 Provider。

提前致谢

4

2 回答 2

2

当使用您推送的路线执行导航时,通过其内部 defaultNavigator.of(context)成为您的小部件树的一部分。但是,该路线不会成为.MaterialAppNavigatorChangeNotifierProviderMaterialApp

您应该使提供者成为您的MaterialApp.

于 2020-04-01T17:59:33.597 回答
2

ChangeNotifier上移MyApp

void main() {
  runApp(ChangeNotifierProvider(
      builder: (context) => ContentDS(),
      child: MyApp()));
}
于 2019-10-24T07:45:25.080 回答