Данные не передаются из Django Rest в приложение Flutter App

Я пытаюсь получить json данные из django api restframework в приложение flutter, но оно ничего не показывает. Даже функция retrieveRecord в main.dart не печатает текст при запуске приложения.

django возвращает json-код на

http://localhost:8000/records/?format=api

он также показывает json без формата на http://localhost:8000/records/?format=json

но в списке просмотров flutter ничего не отображается

Main.dart

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

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Test Phase Assignment',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Test Phase Assigment'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  Client client = http.Client();
  List<AnnSystem> annSystem = [];

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

  _retrieveRecord() async {
    annSystem = [];
    List response = json.decode((await client
            .get(Uri.parse('http://10.0.2.2:8000/records/?format=json')))
        .body);
    response.forEach((element) {
      annSystem.add(AnnSystem.fromMap(element));
    });
    print(response); // it does not print on terminal
    print("function calling"); //it does not print on terminal
    setState(() {});
  }

  _addRecord() {}

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: RefreshIndicator(
        onRefresh: () async {
          _retrieveRecord();
        },
        child: ListView.builder(
          itemCount: annSystem.length,
          itemBuilder: (BuildContext context, int index) {
            return ListTile(
              title: Text(annSystem[index].location),
            );
          },
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _addRecord(),
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

annSystem.dart (class)

import 'dart:convert';
import 'dart:convert';

class AnnSystem {
  int id;
  String tempratures;
  String location;
  String land_area;
  AnnSystem({
    required this.id,
    required this.tempratures,
    required this.location,
    required this.land_area,
  });

  AnnSystem copyWith({
    int? id,
    String? tempratures,
    String? location,
    String? land_area,
  }) {
    return AnnSystem(
      id: id ?? this.id,
      tempratures: tempratures ?? this.tempratures,
      location: location ?? this.location,
      land_area: land_area ?? this.land_area,
    );
  }

  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'tempratures': tempratures,
      'location': location,
      'land_area': land_area,
    };
  }

  factory AnnSystem.fromMap(Map<String, dynamic> map) {
    return AnnSystem(
      id: map['id'],
      tempratures: map['tempratures'],
      location: map['location'],
      land_area: map['land_area'],
    );
  }

  String toJson() => json.encode(toMap());

  factory AnnSystem.fromJson(String source) =>
      AnnSystem.fromMap(json.decode(source));

  @override
  String toString() {
    return 'AnnSystem(id: $id, tempratures: $tempratures, location: $location, land_area: $land_area)';
  }

  @override
  bool operator ==(Object other) {
    if (identical(this, other)) return true;
    
    return other is AnnSystem &&
        other.id == id &&
        other.tempratures == tempratures &&
        other.location == location &&
        other.land_area == land_area;
  }

  @override
  int get hashCode {
    return id.hashCode ^
        tempratures.hashCode ^
        location.hashCode ^
        land_area.hashCode;
  }
}

Django app Urls.py

from django.urls import path
from django.urls.resolvers import URLPattern
from . import views

urlpatterns = [
    path('',views.getRoutes),
    path('records/', views.getRecords),
    path('records/create/', views.createRecord),
    path('records/<str:pk>', views.getRecord),
    path('records/<str:pk>/update/', views.getRecord),
    path('records/<str:pk>/delete/', views.deleteRecord),
]

Views.py

from rest_framework.decorators import api_view
from rest_framework.response import Response
from .serializers import RecordsSerializer
from .models import Records

@api_view(['GET','POST','DELETE'])
def getRoutes(request):
    routes = [
        {
            'Endpoint': '/recordss',
            'method': 'GET',
            'body': None,
            'desciption': 'return an array of all records'
        },
        {
            'Endpoint': '/recordss/id',
            'method': 'GET',
            'body': None,
            'desciption': 'return one single record'
        },
          {
            'Endpoint': '/recordss/create/',
            'method': 'POST',
            'body': {'body':""},
            'desciption': 'create a record in database'
        },
          {
            'Endpoint': '/recrodss/id/update',
            'method': 'PUT',
            'body':  {'body':""},
            'desciption': 'return one single record'
        },

        {
            'Endpoint': '/recrodss/id/delete',
            'method': 'DELETE',
            'body': None,
            'desciption': 'Deletes and Exiting note'
        },
        
    ]

   

@api_view(['GET'])
def getRecords(request):
    records = Records.objects.all()
    serializer = RecordsSerializer(records, many=True)
    return Response(serializer.data)

@api_view(['GET'])
def getRecord(request,pk):
    record = Records.objects.get(id=pk)
    serializer = RecordsSerializer(record, many=False)
    return Response(serializer.data)


@api_view(['POST'])
def createRecord(request):
    data = request.data
    record = Records
    
    Records.objects.create(
        tempratures = data['tempratures'],
        location = data['location'],
        land_area = data['land_area']
    )
    serializer = RecordsSerializer(record, many=True)
    return Response(serializer.data)

@api_view(['PUT'])
def updateRecord(request,pk):
    data = request.data
    record = Records.objects.get(id=pk)
    serializer = RecordsSerializer(record, data=request.PUT)
    if serializer.is_valid():
        serializer.save()
    return Response(serializer.data)

@api_view(['DELETE'])
def deleteRecord(request,pk):
    record = Records.objects.get(id=pk)
    record.delete()
    return Response("Record has been deleted")

serilizer.py

from django.db.models import fields
from rest_framework.serializers import ModelSerializer, Serializer

from .models import Records


class RecordsSerializer(ModelSerializer):
    class Meta:
        model = Records
        fields = ['id', 'tempratures', 'location', 'land_area']

в settings.py


ALLOWED_HOSTS = [
    '10.0.2.2',
    'localhost',
]


Вернуться на верх