Flutter未显示API数据

r9f1avp5  于 2023-02-20  发布在  Flutter
关注(0)|答案(1)|浏览(155)

当我尝试从jsonplaceholder API中提取数据并将其放在屏幕上时,我没有遇到任何问题,但当我尝试使用相同的代码更改www.example.com网站上此链接(https://reqres.in/api/users?page=2)中的数据时reqres.io,仅通过更改API和模型,屏幕上出现文本no data. I'm get it can help me?

我的JsonPlaceHolder项目

主省道

import 'package:flutter/material.dart';
import 'package:my_app/models/json_model.dart';

import 'service/api_service.dart';

void main() =\> runApp(const MyApp());

class MyApp extends StatelessWidget {
const MyApp({super.key});

@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Material App',
home: Scaffold(
appBar: AppBar(
title: const Text('Json Deneme'),
),
body: const Home(),
),
);
}
}

class Home extends StatefulWidget {
const Home({super.key});

@override
State\<Home\> createState() =\> \_HomeState();
}

class \_HomeState extends State\<Home\> {
List\<JsonModel\>? \_postItems;
bool \_isLoading = false;
String? \_errorMessage;

@override
void initState() {
super.initState();
loadData();
}

Future\<void\> loadData() async {
setState(() {
_isLoading = true;
_errorMessage = null;
});
try {
final postItems = await Api.fetchApi();
setState(() {
_postItems = postItems;
_isLoading = false;
});
} catch (e) {
setState(() {
_isLoading = false;
_errorMessage = 'Error fetching data: $e';
});
}
}

@override
Widget build(BuildContext context) {
if (\_isLoading) {
return const Center(child: CircularProgressIndicator());
} else if (\_postItems == null || \_postItems!.isEmpty) {
return const Center(child: Text('No Data'));
} else {
return ListView.builder(
itemCount: \_postItems!.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(\_postItems!\[index\].name),
);
},
);
}
}
}`

API服务.dart

`import 'dart:io';

import 'package:my_app/models/json_model.dart';
import 'package:dio/dio.dart';

class Api {
static Future<List<JsonModel>?> fetchApi() async {
final res = await Dio().get("https://jsonplaceholder.typicode.com/users");
if (res.statusCode == HttpStatus.ok) {
final data = res.data!;
if (data is List) {
return data.map((e) =\> JsonModel.fromMap(e)).toList();
}
}
return <JsonModel>[];
}
}
`

结论

conclusion

我在www.example.com的项目reqres.in

主省道

`import 'package:flutter/material.dart';
import 'package:my_app/models/json_model.dart';

import 'service/api_service.dart'; 

void main() =\> runApp(const MyApp());

class MyApp extends StatelessWidget {
const MyApp({super.key});

@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Material App',
home: Scaffold(
appBar: AppBar(
title: const Text('Json Deneme'),
),
body: const Home(),
),
);
}
}

class Home extends StatefulWidget {
const Home({super.key});

@override
State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
List<ReqresModel>? _postItems;
bool _isLoading = false;
String? _errorMessage;

@override
void initState() {
super.initState();
loadData();
}

Future<void> loadData() async {
setState(() {
_isLoading = true;
_errorMessage = null;
});
try {
final postItems = await Api.fetchApi();
setState(() {
_postItems = postItems;
_isLoading = false;
});
} catch (e) {
setState(() {
_isLoading = false;
_errorMessage = 'Error fetching data: $e';
}); 
}
}

@override
Widget build(BuildContext context) {
if (_isLoading) {
return const Center(child: CircularProgressIndicator());
} else if (_postItems == null || _postItems!.isEmpty) { 
return const Center(child: Text('No Data'));
} else {
return ListView.builder(
itemCount: _postItems!.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(\_postItems!\[index\].data\[index\].firstName),
);
},
);
}
}
}`

API程序接口服务.dart

`import 'dart:io';

 import 'package:my_app/models/json_model.dart';
 import 'package:dio/dio.dart';

 class Api {
 static Future<List<ReqresModel>?> fetchApi() async {
 final res = await Dio().get("https://reqres.in/api/users?page=2");
 if (res.statusCode == HttpStatus.ok) {
 final data = res.data!;
 if (data is List) {
 return data.map((e) => ReqresModel.fromMap(e)).toList();
 }
 }
 return <ReqresModel>[];
 }
 }`

结论

conclusion

谢谢

我用Postman发的API,没有问题,我觉得不是API的问题,抱歉我的英语不好

0x6upsns

0x6upsns1#

使用以下代码将api_service.dart更改为reqres.in项目。第一个API直接返回List,但第二个API返回Json,其中data作为List

已编辑

    • 主省道**
import 'package:flutter/material.dart';
import 'package:my_app/models/json_model.dart';

import 'service/api_service.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Material App',
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Json Deneme'),
        ),
        body: const Home(),
      ),
    );
  }
}

class Home extends StatefulWidget {
  const Home({super.key});

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  List<ReqresModel>? _postItems;
  bool _isLoading = false;
  String? _errorMessage;

  @override
  void initState() {
    super.initState();
    loadData();
  }

  Future<void> loadData() async {
    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });
    try {
      final postItems = await Api.fetchApi();
      setState(() {
        _postItems = postItems;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
        _errorMessage = 'Error fetching data: $e';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading) {
      return const Center(child: CircularProgressIndicator());
    } else if (_postItems == null || _postItems!.isEmpty) {
      return const Center(child: Text('No Data'));
    } else {
      return ListView.builder(
        itemCount: _postItems!.length,
        itemBuilder: (context, index) {
          return ListTile(
            title: Text(_postItems![index].firstName),//Updated here
          );
        },
      );
    }
  }
}
    • 应用程序接口服务. dart**
import 'dart:io';

import 'package:my_app/models/json_model.dart';
import 'package:dio/dio.dart';

class Api {
  static Future<List<ReqresModel>?> fetchApi() async {
    final res = await Dio().get("https://reqres.in/api/users?page=2");
    if (res.statusCode == HttpStatus.ok) {
      final data = res.data!['data'];//Updated here
      if (data is List) {
        return data.map((e) => ReqresModel.fromMap(e)).toList();
      }
    }
    return <ReqresModel>[];
  }
}
    • 请求模型**-应更新
//Updated here
class ReqresModel {
  int? id;
  String? email;
  String? firstName;
  String? lastName;
  String? avatar;

  ReqresModel(
      {this.id, this.email, this.firstName, this.lastName, this.avatar});

  ReqresModel.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    email = json['email'];
    firstName = json['first_name'];
    lastName = json['last_name'];
    avatar = json['avatar'];
  }
}

相关问题