0

我可以在 main.dart 文件的 init 方法中使用提供程序吗?

我尝试使用 SchedulerBinding.instance.addPostFrameCallback 方法作为回调,但出现异常。

import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutterdev/pages/product_list.dart';
import 'package:flutterdev/state/user.dart';
import 'package:provider/provider.dart';
// import 'package:flutter/rendering.dart';

import './pages/auth.dart';
import './pages/products_admin.dart';
import './pages/products.dart';
import './pages/product.dart';
import './state/products.dart';
import './state/user.dart';
import './models/product.dart';

void main() {
  // debugPaintSizeEnabled = true;
  // debugPaintBaselinesEnabled = true;
  // debugPaintPointersEnabled = true;
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _MyAppState();
  }
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    SchedulerBinding.instance.addPostFrameCallback((_) {

      UserProvider userProvider = Provider.of<UserProvider>(context);
      userProvider.autoAuthenticate();

    });

    // () async {
    //  await Future.delayed(Duration.zero);

    //}();
  }

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(builder: (_) => ProductsProvider()),
        ChangeNotifierProvider(builder: (_) => UserProvider()),
      ],
      child: MaterialApp(
        // debugShowMaterialGrid: true,
        theme: ThemeData(
            brightness: Brightness.light,
            primarySwatch: Colors.deepOrange,
            accentColor: Colors.deepPurple,
            buttonColor: Colors.deepPurple),

        // home: AuthPage(),
        routes: {
          '/': (BuildContext context) =>
              Consumer<UserProvider>(builder: (context, userProvider, _) {
                final ProductsProvider productsProvider =
                    Provider.of<ProductsProvider>(context);
                String token = "";

                if (userProvider.authenticatedUser != null) {
                  token = userProvider.authenticatedUser.token;
                }

                return userProvider.authenticatedUser == null
                    ? AuthPage()
                    : ProductListPage(productsProvider, token);
              }),

        },
      ),
    );
  }
}

我遇到了一个例外。我不知道如何提升小部件上方的多提供者以使其工作。我试图将其移至 createstate 和 main 方法。我不明白该怎么做。


flutter: ══╡ EXCEPTION CAUGHT BY SCHEDULER LIBRARY ╞═════════════════════════════════════════════════════════
flutter: The following ProviderNotFoundError was thrown during a scheduler callback:
flutter: Error: Could not find the correct Provider<UserProvider> above this MyApp Widget
flutter:
flutter: To fix, please:
flutter:
flutter:   * Ensure the Provider<UserProvider> is an ancestor to this MyApp Widget
flutter:   * Provide types to Provider<UserProvider>
flutter:   * Provide types to Consumer<UserProvider>
flutter:   * Provide types to Provider.of<UserProvider>()
flutter:   * Always use package imports. Ex: `import 'package:my_app/my_code.dart';
flutter:   * Ensure the correct `context` is being used.
flutter:
flutter: If none of these solutions work, please file a bug at:


4

1 回答 1

2

下面的代码有效。我将提供程序设置移动到 runApp 并在 MyApp 中接收 userprovider 作为参数。

 runApp(
    ChangeNotifierProvider<UserProvider>(
      builder: (ctx) => UserProvider(),

     child:    Consumer<UserProvider>(
        builder: (context, userprovider, _) {
         return MyApp(userprovider);
        }
      ) 
      ),    
  );


于 2019-08-09T03:50:32.273 回答