扑来:nosuchmethoderror:方法' []'被称为null。接收器:null尝试致电:[]('name&quot)

发布于 2025-02-08 16:29:48 字数 9568 浏览 2 评论 0原文

我试图使用API​​和Bloc Builder在颤动中获取数据。但是我在运行集团时会遇到错误。这是我的代码。我正在使用快速的API和Flutter Bloc包装,谢谢。

main.dart

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:footballplayers/services/api_services.dart';

import 'homeScreen.dart';

void main() {
  runApp(const MyApp());
}

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

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MultiRepositoryProvider(
        providers: [
          RepositoryProvider(
            create: (context) => ApiServices(),
          ),
        ],
        child: HomeScreen(),
      ),
    );
  }
}

homescreen.dart

// ignore_for_file: public_member_api_docs, sort_constructors_first
import 'package:flutter/material.dart';
import 'package:flutter/src/foundation/key.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:footballplayers/bloc/recipe_bloc.dart';

import 'package:footballplayers/models/recipe_model.dart';
import 'package:footballplayers/services/api_services.dart';

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

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) =>
          RecipeBloc(RepositoryProvider.of<ApiServices>(context))
            ..add(GetRecipeEvent()),
      child: Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.white,
          title: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                Icons.restaurant_menu,
                color: Colors.black,
              ),
              Text(
                'FoodRecipe',
                style: TextStyle(
                  color: Colors.black,
                  fontWeight: FontWeight.bold,
                ),
              )
            ],
          ),
        ),
        body: BlocBuilder<RecipeBloc, RecipeState>(
          builder: (context, state) {
            if (state is RecipeLoading) {
              return Center(
                child: CircularProgressIndicator(),
              );
            }
            if (state is RecipeLoaded) {
              return Container(
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(10),
                ),
                padding: EdgeInsets.all(10),
                child: ListView.builder(
                    shrinkWrap: true,
                    itemCount: state.recipeData.length,
                    itemBuilder: (context, index) {
                      return recipeCard(
                        imgUrl: state.recipeData[index].imgUrl,
                        recipeName: state.recipeData[index].name,
                        rating: state.recipeData[index].rating,
                        totalTime: state.recipeData[index].totalTime,
                      );
                    }),
              );
            } else {
              throw Exception('Something went wrong');
            }
          },
        ),
      ),
    );
  }
}

class recipeCard extends StatelessWidget {
  String imgUrl;
  String recipeName;
  double rating;
  String totalTime;
  recipeCard({
    Key? key,
    required this.imgUrl,
    required this.recipeName,
    required this.rating,
    required this.totalTime,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Card(
      child: Column(children: [
        ClipRRect(
            borderRadius: BorderRadius.circular(10),
            child: Image.network(
              imgUrl,
              fit: BoxFit.cover,
            )),
        Text(
          recipeName,
          textAlign: TextAlign.center,
          style: TextStyle(
            fontWeight: FontWeight.bold,
            fontSize: 18,
          ),
        ),
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Container(
                padding: EdgeInsets.all(5),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(5),
                  color: Color.fromARGB(255, 18, 224, 63),
                ),
                child: Text(
                  rating.toString(),
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 15,
                  ),
                ),
              ),
              Container(
                padding: EdgeInsets.all(5),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(5),
                  color: Color.fromARGB(255, 70, 18, 224),
                ),
                child: Text(
                  totalTime,
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    color: Colors.white,
                    fontWeight: FontWeight.bold,
                    fontSize: 15,
                  ),
                ),
              ),
            ],
          ),
        ),
      ]),
    );
  }
}

apiservices.dart

    import 'dart:convert';
    
    import 'package:flutter/material.dart';
    import 'package:footballplayers/models/recipe_model.dart';
    import 'package:http/http.dart' as http;
    
    class ApiServices {
      List<RecipeModel> recipeList = [];
    
      Future<List<RecipeModel>> getRecipe() async {
        final uri = Uri.https(
            'yummly2.p.rapidapi.com', '/feeds/list', {'limit': '24', 'start': '0'});
    
        final response = await http.get(
          uri,
          headers: {
            'X-RapidAPI-Key': '80cb4acef6mshf3b62df4bcdc92ap1b8e20jsna293a3b01f0f',
            'X-RapidAPI-Host': 'yummly2.p.rapidapi.com',
          },
        );
        final data = jsonDecode(response.body);
        final values = data['feed'];
        for (int i = 0; i < values.length; i++) {
          if (values[i]['content']['details']['name'] != null) {
            RecipeModel recipeModel = RecipeModel(
              name: values[i]['content']['details']['name'] as String,
              imgUrl: values[i]['content']['details']['images'][0]['hostedLargeUrl']
                  as String,
              totalTime: values[i]['content']['details']['totalTime'] as String,
              rating: values[i]['content']['details']['rating'] as double,
            );
            recipeList.add(recipeModel);
          }
        }
        return recipeList;
      }
    }

**RecipeModel.dart**

// ignore_for_file: public_member_api_docs, sort_constructors_first
class RecipeModel {
  String name;
  String imgUrl;
  String totalTime;
  double rating;
  RecipeModel({
    required this.name,
    required this.imgUrl,
    required this.totalTime,
    required this.rating,
  });

  factory RecipeModel.fromJson(Map<String, dynamic> json) {
    return RecipeModel(
      name: json['name'],
      imgUrl: json['images'][0]['hostedLargeUrl'],
      totalTime: json['totalTime'],
      rating: json['rating'],
    );
  }

  @override
  String toString() {
    return 'RecipeModel(name: $name, imgUrl: $imgUrl, totalTime: $totalTime, rating: $rating)';
  }
}

recipebloc.dart

import 'package:bloc/bloc.dart';
import 'package:footballplayers/models/recipe_model.dart';
import 'package:footballplayers/services/api_services.dart';
import 'package:meta/meta.dart';

part 'recipe_event.dart';
part 'recipe_state.dart';

class RecipeBloc extends Bloc<RecipeEvent, RecipeState> {
  final ApiServices apiServices;
  List<RecipeModel> recipeD = [];
  RecipeBloc(this.apiServices) : super(RecipeInitial()) {
    on<GetRecipeEvent>((event, emit) async {
      emit(RecipeLoading());
      final activity = await apiServices.getRecipe();
      recipeD = apiServices.recipeList;

      emit(RecipeLoaded(recipeData: recipeD));
    });
  }
}

repipeblocevent.dart.dart

part of 'recipe_bloc.dart';

@immutable
abstract class RecipeEvent {}

class GetRecipeEvent extends RecipeEvent {}

配方Blocstate.dart

// ignore_for_file: public_member_api_docs, sort_constructors_first
part of 'recipe_bloc.dart';

abstract class RecipeState {}

class RecipeInitial extends RecipeState {}

class RecipeLoading extends RecipeState {}

class RecipeLoaded extends RecipeState {
  List<RecipeModel> recipeData;
  RecipeLoaded({
    required this.recipeData,
  });

  @override
  String toString() => 'RecipeLoaded(recipeData: $recipeData)';
}

控制台中的错误 颤音:诺舒特莫尔:方法'[]'被称为null。 接收器:null 尝试致电:

响应

”在此处输入图像描述

预先感谢Stackoverflow社区。

I was trying to fetch data using API and Bloc builder in a flutter. But I am getting an error while running the bloc. Here is my code. I am using rapid Api and flutter bloc package Thanks.

Main.dart

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:footballplayers/services/api_services.dart';

import 'homeScreen.dart';

void main() {
  runApp(const MyApp());
}

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

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MultiRepositoryProvider(
        providers: [
          RepositoryProvider(
            create: (context) => ApiServices(),
          ),
        ],
        child: HomeScreen(),
      ),
    );
  }
}

HomeScreen.dart

// ignore_for_file: public_member_api_docs, sort_constructors_first
import 'package:flutter/material.dart';
import 'package:flutter/src/foundation/key.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:footballplayers/bloc/recipe_bloc.dart';

import 'package:footballplayers/models/recipe_model.dart';
import 'package:footballplayers/services/api_services.dart';

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

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) =>
          RecipeBloc(RepositoryProvider.of<ApiServices>(context))
            ..add(GetRecipeEvent()),
      child: Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.white,
          title: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                Icons.restaurant_menu,
                color: Colors.black,
              ),
              Text(
                'FoodRecipe',
                style: TextStyle(
                  color: Colors.black,
                  fontWeight: FontWeight.bold,
                ),
              )
            ],
          ),
        ),
        body: BlocBuilder<RecipeBloc, RecipeState>(
          builder: (context, state) {
            if (state is RecipeLoading) {
              return Center(
                child: CircularProgressIndicator(),
              );
            }
            if (state is RecipeLoaded) {
              return Container(
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(10),
                ),
                padding: EdgeInsets.all(10),
                child: ListView.builder(
                    shrinkWrap: true,
                    itemCount: state.recipeData.length,
                    itemBuilder: (context, index) {
                      return recipeCard(
                        imgUrl: state.recipeData[index].imgUrl,
                        recipeName: state.recipeData[index].name,
                        rating: state.recipeData[index].rating,
                        totalTime: state.recipeData[index].totalTime,
                      );
                    }),
              );
            } else {
              throw Exception('Something went wrong');
            }
          },
        ),
      ),
    );
  }
}

class recipeCard extends StatelessWidget {
  String imgUrl;
  String recipeName;
  double rating;
  String totalTime;
  recipeCard({
    Key? key,
    required this.imgUrl,
    required this.recipeName,
    required this.rating,
    required this.totalTime,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Card(
      child: Column(children: [
        ClipRRect(
            borderRadius: BorderRadius.circular(10),
            child: Image.network(
              imgUrl,
              fit: BoxFit.cover,
            )),
        Text(
          recipeName,
          textAlign: TextAlign.center,
          style: TextStyle(
            fontWeight: FontWeight.bold,
            fontSize: 18,
          ),
        ),
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Container(
                padding: EdgeInsets.all(5),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(5),
                  color: Color.fromARGB(255, 18, 224, 63),
                ),
                child: Text(
                  rating.toString(),
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 15,
                  ),
                ),
              ),
              Container(
                padding: EdgeInsets.all(5),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(5),
                  color: Color.fromARGB(255, 70, 18, 224),
                ),
                child: Text(
                  totalTime,
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    color: Colors.white,
                    fontWeight: FontWeight.bold,
                    fontSize: 15,
                  ),
                ),
              ),
            ],
          ),
        ),
      ]),
    );
  }
}

ApiServices.dart

    import 'dart:convert';
    
    import 'package:flutter/material.dart';
    import 'package:footballplayers/models/recipe_model.dart';
    import 'package:http/http.dart' as http;
    
    class ApiServices {
      List<RecipeModel> recipeList = [];
    
      Future<List<RecipeModel>> getRecipe() async {
        final uri = Uri.https(
            'yummly2.p.rapidapi.com', '/feeds/list', {'limit': '24', 'start': '0'});
    
        final response = await http.get(
          uri,
          headers: {
            'X-RapidAPI-Key': '80cb4acef6mshf3b62df4bcdc92ap1b8e20jsna293a3b01f0f',
            'X-RapidAPI-Host': 'yummly2.p.rapidapi.com',
          },
        );
        final data = jsonDecode(response.body);
        final values = data['feed'];
        for (int i = 0; i < values.length; i++) {
          if (values[i]['content']['details']['name'] != null) {
            RecipeModel recipeModel = RecipeModel(
              name: values[i]['content']['details']['name'] as String,
              imgUrl: values[i]['content']['details']['images'][0]['hostedLargeUrl']
                  as String,
              totalTime: values[i]['content']['details']['totalTime'] as String,
              rating: values[i]['content']['details']['rating'] as double,
            );
            recipeList.add(recipeModel);
          }
        }
        return recipeList;
      }
    }

**RecipeModel.dart**

// ignore_for_file: public_member_api_docs, sort_constructors_first
class RecipeModel {
  String name;
  String imgUrl;
  String totalTime;
  double rating;
  RecipeModel({
    required this.name,
    required this.imgUrl,
    required this.totalTime,
    required this.rating,
  });

  factory RecipeModel.fromJson(Map<String, dynamic> json) {
    return RecipeModel(
      name: json['name'],
      imgUrl: json['images'][0]['hostedLargeUrl'],
      totalTime: json['totalTime'],
      rating: json['rating'],
    );
  }

  @override
  String toString() {
    return 'RecipeModel(name: $name, imgUrl: $imgUrl, totalTime: $totalTime, rating: $rating)';
  }
}

RecipeBloc.dart

import 'package:bloc/bloc.dart';
import 'package:footballplayers/models/recipe_model.dart';
import 'package:footballplayers/services/api_services.dart';
import 'package:meta/meta.dart';

part 'recipe_event.dart';
part 'recipe_state.dart';

class RecipeBloc extends Bloc<RecipeEvent, RecipeState> {
  final ApiServices apiServices;
  List<RecipeModel> recipeD = [];
  RecipeBloc(this.apiServices) : super(RecipeInitial()) {
    on<GetRecipeEvent>((event, emit) async {
      emit(RecipeLoading());
      final activity = await apiServices.getRecipe();
      recipeD = apiServices.recipeList;

      emit(RecipeLoaded(recipeData: recipeD));
    });
  }
}

RecipeBlocEvent.dart

part of 'recipe_bloc.dart';

@immutable
abstract class RecipeEvent {}

class GetRecipeEvent extends RecipeEvent {}

RecipeBlocState.dart

// ignore_for_file: public_member_api_docs, sort_constructors_first
part of 'recipe_bloc.dart';

abstract class RecipeState {}

class RecipeInitial extends RecipeState {}

class RecipeLoading extends RecipeState {}

class RecipeLoaded extends RecipeState {
  List<RecipeModel> recipeData;
  RecipeLoaded({
    required this.recipeData,
  });

  @override
  String toString() => 'RecipeLoaded(recipeData: $recipeData)';
}

Error in Console
flutter: NoSuchMethodError: The method '[]' was called on null.
Receiver: null
Tried calling:

Response.body

enter image description here

Thanks in advance for stackoverflow community.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文