在 Flutter 中需要 Providers 的帮助

Need assistance with Providers in Flutter

我正在努力了解 Flutter 中的提供者...但是在学习了一些教程之后,我仍然面临一些问题。

当我尝试 运行 这段代码时,它给我一个错误

Error: Could not find the correct Provider above this MyHomePage Widget

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:provider_way/MyHomePageViewModel.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => MyHomePageViewModel(),
      child: Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Consumer<MyHomePageViewModel>(
                builder: (context, viewModel, child) {
                  return Text(viewModel.text);
                },
              ),
            ],
          ),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () =>
              Provider.of<MyHomePageViewModel>(context, listen: false)
                  .onClicked(),
          tooltip: 'Increment',
          child: Icon(Icons.add),
        ), // This trailing comma makes auto-formatting nicer for build methods.
      ),
    );
  }
}



import 'package:flutter/foundation.dart';

class MyHomePageViewModel extends ChangeNotifier {
  String text = 'Initial text';

  void onClicked() {
    text = 'Something was clicked';
    notifyListeners();
  }
}

我发现此示例的网站将其用作

Provider.of<MainViewModel>(context, listen: false).onClicked(),

但这也不管用...

在显示需要提供程序的小部件之前,您需要在构建页面之前创建该特定提供程序。

在下方查看代码的工作示例。

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:provider_way/MyHomePageViewModel.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (_) => MyHomePageViewModel(),
      builder: (_, __) => MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: MyHomePage(title: 'Flutter Demo Home Page'),
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Consumer<MyHomePageViewModel>(
              builder: (context, viewModel, child) {
                return Text(viewModel.text);
              },
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () =>
            Provider.of<MyHomePageViewModel>(context, listen: false)
                .onClicked(),
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

import 'package:flutter/foundation.dart';

class MyHomePageViewModel extends ChangeNotifier {
  String text = 'Initial text';

  void onClicked() {
    text = 'Something was clicked';
    notifyListeners();
  }
}

在您的提供商代码中,您是否有一个 class 定义如下:

class MyHomePageViewModel extends ChangeNotifier {
  // your stuff here, like getter and setters, methods, etc
}

class 将处理您的状态的所有集中化,基本上按照您希望的方式行事 - 提供者。