繁体   English   中英

Flutter Bloc-为什么我在使用 bloc 时得到错误状态作为输出,

[英]Flutter Bloc-why i am getting error state as output while using bloc ,

颤振集团状态管理问题

我正在使用 openweatherapi 学习 bloc,但我得到 Errorstate(Weathererrorstate) 作为输出,不理解 bloc 状态管理,

没有在代码中添加我用不包含在代码中的 blocpProvider

主页.dart


TextEditingController textEditingController = TextEditingController();

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    {
      Repository repository = Repository();
      return MaterialApp(
          home: Scaffold(body: BlocBuilder<WeatherBloc, WeatherState>(
        builder: (context, state) {
          if (state is WeatherInitialstate) {
            context.read<WeatherBloc>().add(
                loadWeatherDataEvent(location: textEditingController.text));

            return const Center(
              child: CircularProgressIndicator(color: Colors.red,),
            );
          } else if (state is WeatherLoadingstate) {
            return const Center(
              child: CircularProgressIndicator(color: Colors.yellow,),
            );
          } else if (state is Weatherloadedstate) {
            return buildnew(state.weathermodel);
          } else if (state is WeatherErrorstate) {
            return const Center(
              child: Text('error state'),
            );
          }
          return const Center(
            child: Text('error'),
          );
        },
      )));
    }
  }
}

 

Widget buildnew(Weather weather) {
  return Column(
    children: [
      TextField(
          controller: textEditingController,
          onChanged: (value) {
        
          },
          decoration: InputDecoration(
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(30),
            ),
          )),
      Text(weather.cityname.toString())
    ],
  );
}

网络文件.dart


class Repository {
  Future<Weather?> getdata({required String location}) async {
    String url =
        'https://api.openweathermap.org/data/2.5/weather?q=$location&appid=c1b66d13f980552b4cdd1123f5c20c72#';

    final result = await http.get(Uri.parse(url));
    if (result.statusCode != 200) {
      return null;
    }
    final decodeddata = jsonDecode(result.body);
 
    return Weather.fromJson(decodeddata);
  }
}

天气事件.dart

part of 'weather_bloc.dart';

abstract class WeatherEvent {
  WeatherEvent();
}

class loadWeatherDataEvent extends WeatherEvent {
  final String location;

  loadWeatherDataEvent( {required this.location});
}

天气状况.dart

part of 'weather_bloc.dart';

@immutable
abstract class WeatherState {}

class WeatherInitialstate extends WeatherState {}

class WeatherLoadingstate extends WeatherState {}

class Weatherloadedstate extends WeatherState {
  final Weather weathermodel;

  Weatherloadedstate({required this.weathermodel});
}
class WeatherErrorstate extends WeatherState{}

天气块.dart

import 'package:bloc/bloc.dart';
import 'package:meta/meta.dart';
import 'package:weatherapi/Model/weathermodel.dart';
import 'package:weatherapi/Network/Networkfile.dart';

part 'weather_event.dart';
part 'weather_state.dart';

class WeatherBloc extends Bloc<WeatherEvent, WeatherState> {
  final Repository repository;

  WeatherBloc({required this.repository}) : super(WeatherInitialstate()) {
    on<WeatherEvent>((event, emit) async {
      if (event is loadWeatherDataEvent) {
        emit(WeatherLoadingstate());

        final Weather? weather =
            await repository.getdata(location: event.location);
        if (weather == null) {
          emit(WeatherErrorstate());
        } else {
          emit(Weatherloadedstate(weathermodel: weather));
        }
      }
    });
  }
}

您经过的位置尚未设置(还没有?)。

这就是 API 返回错误代码的原因,这反过来又会导致您的存储库返回 null。

如果您希望用户输入一个位置,那么您至少需要等待他们这样做,而不是在第一次构建时立即触发您的加载事件。 也许当他们完成输入数据时按下按钮? 你决定。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM