在 onGenerateRoute 中使用 BlocProvider 注入存储库

Posted

技术标签:

【中文标题】在 onGenerateRoute 中使用 BlocProvider 注入存储库【英文标题】:Inject Repository with BlocProvider in onGenerateRoute 【发布时间】:2021-07-20 17:32:48 【问题描述】:

我正在尝试学习 bloc for flutter,但遇到了一个问题,

我正在尝试基于BLOC weather app 制作一个天气应用程序,但我希望由 onGenerateRoute 完成路由,问题是类的方法必须是静态的,而我传递的存储库是final 字段,通过类的构造函数初始化。

代码-

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:weather/bloc/weather_bloc.dart';
import 'package:weather/repositories/WeatherRepository.dart';
import 'package:weather/screens/errors/404.dart';
import 'package:weather/screens/loading/splashscreen.dart';

class WeatherRouter 
  final WeatherRepository weatherRepository;

  WeatherRouter(this.weatherRepository);
  
  static Route<dynamic> routes(RouteSettings settings) 
    //Uncomment below line as needed
    // final args = settings.arguments;

    switch (settings.name) 
      case '/':
        return MaterialPageRoute(builder: (context) => SplashScreen());
        break;
      case 'weather':
        return MaterialPageRoute(
            builder: (context) => BlocProvider(
                create: (context) =>
                    WeatherBloc(weatherRepository: weatherRepository)));
        break;
      default:
        return MaterialPageRoute(builder: (context) => FourZeroFour());
    
  

错误 -

【问题讨论】:

【参考方案1】:

为什么不删除关键字static

import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:weather/bloc/weather_bloc.dart';
import 'package:weather/repositories/WeatherRepository.dart';
import 'package:weather/screens/errors/404.dart';
import 'package:weather/screens/loading/splashscreen.dart';

class WeatherRouter 
  final WeatherRepository weatherRepository;

  WeatherRouter(this.weatherRepository);
  
 Route<dynamic> routes(RouteSettings settings)  // <-- remove static from here!
    //Uncomment below line as needed
    // final args = settings.arguments;

    switch (settings.name) 
      case '/':
        return MaterialPageRoute(builder: (context) => SplashScreen());
        break;
      case 'weather':
        return MaterialPageRoute(
            builder: (context) => BlocProvider(
                create: (context) =>
                    WeatherBloc(weatherRepository: weatherRepository)));
        break;
      default:
        return MaterialPageRoute(builder: (context) => FourZeroFour());
    
  

查看this 以获取有关如何将flutter_bloc 与routeGenerator 一起使用的参考;)

【讨论】:

以上是关于在 onGenerateRoute 中使用 BlocProvider 注入存储库的主要内容,如果未能解决你的问题,请参考以下文章

在 onGenerateRoute 中使用 BlocProvider 注入存储库

使用带有 Flutter 后退按钮的 onGenerateRoute 时断言失败

Flutter Web-Proper 方式使用 onGenerateRoute 和 routes 作为 MaterialApp 的属性

Flutter onGenerateRoute 路由管理

BZOJ1123: [POI2008]BLO

AC日记——[POI2008]BLO-Blockade 洛谷 [POI2008]BLO-Blockade