Home > Enterprise >  Invalid argument(s): No host specified in URI file flutter api problem
Invalid argument(s): No host specified in URI file flutter api problem

Time:08-15

I'm trying to create detail page for my news page that i create with using api. This is my main page:

import 'package:flutter/material.dart';
import 'package:halkaarzhisseler/models/apis/economy_api.dart';
import 'package:http/http.dart' as http;

import 'haberdetail.dart';




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

  @override
  State<Economy> createState() => _EconomyState();
}

class _EconomyState extends State<Economy> {
  ScrollController? controller;
  final scaffoldKey = GlobalKey<ScaffoldState>();
  final url = Uri.parse('https://api.collectapi.com/news/getNews?country=tr&tag=economy');
  var counter;
  Economylist? haberResult;

  Future callHaber() async {
    try{
      Map<String, String> requestHeaders = {
        'Content-Type': 'application/json',
        'Authorization': 'apikey xxx'
      };
      final response = await http.get(url,headers:requestHeaders);

      if(response.statusCode == 200){
        var result = economylistFromJson(response.body);

        if(mounted);
        setState(() {
          counter = counter = result.result.length;
          haberResult = result;
        });
        return result;
      } else {
        print(response.statusCode);
      }
    } catch(e) {
      print(e.toString());
    }
  }
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    callHaber();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: false,
        automaticallyImplyLeading: false,
        title: Text(
            'Ekonomi Haberleri'
        ),
      ),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: counter != null ?

          ListView.builder(
              itemCount: counter,
              itemBuilder: (context, index){
                return Card(
                  child: ListTile(
                      title: Text(haberResult?.result[index].name??""),
                      subtitle: Text(haberResult?.result[index].source??""),
                leading: CircleAvatar(
                backgroundImage: NetworkImage(haberResult?.result[index].image??""),),


                      onTap: () => Navigator.push(
                        context, MaterialPageRoute(builder: (context) => HaberDetailScreen(haberResult?.result[index].image??"", haberResult?.result[index].name??"", haberResult?.result[index].source??""))),
                  ),
                );
              }) : Center(child: CircularProgressIndicator(

          )),
        ),
      ),
    );

  }
}

This is my detail page:

import 'package:flutter/material.dart';

class HaberDetailScreen extends StatelessWidget {
  String title;
  String subtitle;
  String image;
  HaberDetailScreen(this.title,this.subtitle,this.image);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Detail Page'),

      ),
      body: Row(
        children: [
          Column(
            children: [
              Image.network(image),
            ],
          ),
          Column(


            crossAxisAlignment: CrossAxisAlignment.center,

            children: <Widget>[

              Padding(
                padding: const EdgeInsets.all(8.0),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Text(title,style: TextStyle(fontSize: 18, fontWeight: FontWeight.w900),),
                  ],
                ),
              ),
              Divider(height: 3.6,),
              SizedBox(height: 50,),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: Center(
                  child: Text(subtitle,style: TextStyle(fontSize: 20,fontWeight: FontWeight.w600), textAlign: TextAlign.center,),
                ),
              )
            ],
          ),
        ],
      ),

    );
  }
}

I get error at image: enter image description here

What am i doing wrong? How can i fix this? Thanks for your help

CodePudding user response:

The issue is with passing positioned argument. Image should be on last

 (context) => HaberDetailScreen( haberResult?.result[index].name??"", haberResult?.result[index].source??"",haberResult?.result[index].image??"")),

I will highly recommend using named constructor.

class HaberDetailScreen extends StatelessWidget {
  final String title;
  final String subtitle;
  final String? image;
  const HaberDetailScreen({
    Key? key,
    required this.title,
    required this.subtitle,
      this.image,
  }) : super(key: key);


....

 if (image != null) Image.network(image!),

And use the widget like

HaberDetailScreen(subtitle: ,title: ,image: ,)

More about using constructors


Passing empty string and using it have some risk, because you are passing value which can be "" and it is not a valid link.

Try accepting nullable path or

if(image.isNotEmpty)Image.network(image),

Also you can have errorBuilder on to sothing else rather than error text.

Image.network(
  image,
  errorBuilder: (context, error, stackTrace) {
    return Text("Got Error $error");
  },
),

CodePudding user response:

Put a breakpoint at the top of the page where the photo is there, and after that see what the image URL is for your photos.

CodePudding user response:

There might be problem in url you are passing here. Please check whether its valid or not.

 leading: CircleAvatar(
    backgroundImage: NetworkImage(haberResult?.result[index].image??""),), //here

And here:

Column(
            children: [
              Image.network(image),
            ],
          ),

Update: You can add url check like this.

Column(
                children: [
                  if(Uri.parse(image).isAbsolute) Image.network(image),
                ],
              ),
  • Related