簡體   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