发生异常。 _ClientSocketException(主机查找失败:'flutter-api.test')

问题描述 投票:0回答:1
import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;


class Category{
  int id;
  String name;

  Category({
    required this.id,
    required this.name
  });

  factory Category.fromJson(Map<String, dynamic> json) {
    return Category(id: json['id'], name:json['name']);
  }
}

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

  @override
  CategoriesState createState() => CategoriesState();
}


class CategoriesState extends State<Categories> {
  late Future<List<Category>> futureCategories;

  Future<List<Category>> fetchCategories() async {    
    http.Response response = await http.get(
      Uri.parse('http://flutter-api.test/api/categories')
    );

    List categories = jsonDecode(response.body);

    return categories.map((category) => Category.fromJson(category)).toList();


    
  }

  @override
  void initState() {
    super.initState();
    futureCategories = fetchCategories();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar( 
        title: const Text('Categories'),
      ),
      body: FutureBuilder<List<Category>>(
        future: futureCategories,
        builder: (context, snapshot) {
          if(snapshot.hasData){
            return ListView.builder( 
              itemCount: snapshot.data!.length,
              itemBuilder: (context, index) {
                Category category = snapshot.data![index];
                return ListTile(
                  title: Text(category.name)
                );
              },
            );
          }else if(snapshot.hasError){
            return const Text('Something went wrong');
          }
          return const CircularProgressIndicator();
        }
      )
    );
  }
}

这个 flutter 应用程序请求 laravel api 提供来自

的类别列表

http://flutter-api.test/api/categories

我在本地环境中运行了我的 flutter 应用程序,它使用 chrome 浏览器运行良好(出现了类别列表)

但是,当我通过android模拟器运行它时,它不起作用。 它给出了以下错误

发生异常。 _ClientSocketException(主机查找失败:'flutter-api.test')

我已经进入了

<uses-permission android:name="android.permission.INTERNET" />

在 AndroidManifest.xml 文件中

laravel flutter api
1个回答
0
投票

我遇到了这个问题,你解决了吗?

© www.soinside.com 2019 - 2024. All rights reserved.