skip to Main Content

I have a local flask api with a Get method that runs at http://127.0.0.1:5000/diario/aluno/240, which get one student at a time from a local database that I have. I want to run it on my device using Flutter on Visual Studio Code, but I am getting this error, which is displayed on my flutter app (running on my device):

type ‘null’ is not a subtype of type String in type cast.

I never get this error when I use similar (I would say equal) code when I fetch data from the internet. The rest of the app works fine on my device, but every method from my flask API just don’t work – this is just a simplified example.

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

Future<Student> fetchStudent() async {
  final response = await http.get(Uri.parse('http://127.0.0.1:5000/diario/aluno/240'));
  if (response.statusCode == 200) { 
    return Student.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
  } else {    
    throw Exception('Failed to load album');
  }
}
class Student {
  final String name;

const Student({
  required this.name 
});

factory Student.fromJson(Map<String, dynamic>json) {
  return Student(
    name: json['nome'] as String
  );
}
}
void main() => runApp(const MyApp());
class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
  late Future<Student> futureStudent;

@override
void initState() {
    super.initState();
    futureStudent = fetchStudent();
  }
@override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "Fetch Student Api",
      home: Scaffold(
        appBar: AppBar(
          title: Text("Show students"),          
        ),
        body: Center(
          child: FutureBuilder<Student>(
            future: futureStudent,
            builder: ((context, snapshot) {
              if (snapshot.hasData) {
                return Text(snapshot.data!.name);
              } else if (snapshot.hasError) {
                return Text('${snapshot.error}');
              } 
              return const CircularProgressIndicator();
            }
          ),
        ),

      ), 


    )
    );     
     
  }
}

I tried to add name: json['nome'] as String? ?? 'there is no such name', but then the app never shows the real value from the database. Is there anyone who ever runs a local api using Flutter and has faced such problem? I thought it could be a problem of running on different ports too, so I tried adb reverse tcp:5000 tcp:5000, so the machine and my cellphone could run in the same port, but I still get the same error.

2

Answers


  1. Chosen as BEST ANSWER

    The database is in Brazilian Portuguese and so are the name of the columns in Sql Server. My code is in English, not the data. so "nome" is the name of the column, not "name". I've tried to add ? after String, which didn't work, and that wouldn't be necessary because the data in question is not null, there is a value for this id in the specific database


  2. I see from your attached code that you are trying to cast the json['nome'] to String which is not a good solution because it may return null, so you have to cast it to String? to be json['nome'] as String?, and make sure that the key is nome not name.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search