简体   繁体   中英

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

flutter bloc state management issue

i am learning bloc with openweatherapi,but iam getting Errorstate(Weathererrorstate) as output, not understanding with bloc state management,

did'nt added in code i wrapped main app with blocprovider not included in code

homepage.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())
    ],
  );
}

networkfile.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);
  }
}

weatherevent.dart

part of 'weather_bloc.dart';

abstract class WeatherEvent {
  WeatherEvent();
}

class loadWeatherDataEvent extends WeatherEvent {
  final String location;

  loadWeatherDataEvent( {required this.location});
}

weatherstate.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{}

weatherbloc.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));
        }
      }
    });
  }
}

The location you pass is not set (yet?).

That is why the API returns an error code which in turn causes your repository to return null.

If you want the user to enter a location, then you need at least wait for them to do so and not fire your loading event immediately upon first building. Maybe a button to press when they are finished entering their data? You decide.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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