Search code examples
flutterdarturl-launcher

Although there is no error in the application that I want to show the weather from the internet, a white screen appears


launchUrl not working

import 'package:flutter/material.dart';
import 'package:haber_app/data/new_service.dart';
import 'package:haber_app/models/articles.dart';
import 'package:url_launcher/url_launcher.dart';

class Home extends StatefulWidget {
  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  List<Articles> articles = [];

  @override
  void initState() {
    NewsService.getNews().then((value) {
      setState(() {
        articles = value!;
      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Haberler'),
        centerTitle: true,
      ),
      body: Center(
          child: ListView.builder(
              itemCount: articles.length,
              itemBuilder: (context, index) {
                return Card(
                  child: Column(
                    children: [
                      Image.network(articles[index].urlToImage!),
                      ListTile(
                        leading: Icon(Icons.arrow_drop_down_circle),
                        title: Text(articles[index].title!),
                        subtitle: Text(articles[index].author!),
                      ),
                      Padding(
                        padding: const EdgeInsets.all(16.0),
                        child: Text(
                            'açıklama açıklama açıklamaaçıklama açıklamaaçıklama'),
                      ),
                      ButtonBar(
                        alignment: MainAxisAlignment.start,
                        children: [
                          ElevatedButton(
                              onPressed: () async {
                                await launchUrl(articles[index].url);
                              },
                              child: Text('Habere git'))
                        ],
                      )
                    ],
                  ),
                );
              })),
    );
  }
}

Link of the code: https://github.com/ghedtoboss/haber_app


Solution

  • I am making a pull request, check the changes and merge. haber_app/pull/1

    enter image description here

    Changes are on

    source.dart

    class Source {
      String? id;
      String? name;
    
      Source({this.id, this.name});
    
      Source.fromJson(Map<String, dynamic> json) {
        id = json['id'];
        name = json['name'];
      }
    
      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = Map<String, dynamic>();
        data['id'] = id;
        data['name'] = name;
        return data;
      }
    }
    

    news.dart

    import 'articles.dart';
    
    class News {
      String? status;
      int? totalResults;
      List<Articles>? articles;
    
      News({this.status, this.totalResults, this.articles});
    
      News.fromJson(Map<String, dynamic> json) {
        status = json['status'];
        totalResults = json['totalResults'];
        if (json['articles'] != null) {
          articles = <Articles>[];
          json['articles'].forEach((v) {
            print(v);
            articles!.add(Articles.fromJson(v));
          });
        }
      }
    
      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = Map<String, dynamic>();
        data['status'] = status;
        data['totalResults'] = totalResults;
        if (articles != null) {
          data['articles'] = articles!.map((v) => v.toJson()).toList();
        }
        return data;
      }
    }
    

    NewsService

    import 'package:haber_app/models/articles.dart';
    import 'package:haber_app/models/news.dart';
    import 'package:http/http.dart' as http;
    import 'dart:convert';
    
    class NewsService {
      static NewsService _singleton = NewsService._internal();
      NewsService._internal();
    
      factory NewsService() {
        return _singleton;
      }
    
      static Future<List<Articles>?> getNews() async {
        String api =
            'https://newsapi.org/v2/top-headlines?country=tr&category=business&apiKey=0002834b74c04acd987883986ea38f96';
    
        final Uri url = Uri.parse(api);
        final response = await http.post(url);
    
        if (response.body.isNotEmpty) {
          final responseJson = json.decode(response.body);
          News news = News.fromJson(responseJson);
          return news.articles;
        }
        return null;
      }
    }
    
    

    On body

    import 'package:flutter/material.dart';
    import 'package:haber_app/data/new_service.dart';
    import 'package:haber_app/models/articles.dart';
    import 'package:url_launcher/url_launcher.dart';
    
    class Home extends StatefulWidget {
      @override
      State<Home> createState() => _HomeState();
    }
    
    class _HomeState extends State<Home> {
      List<Articles> articles = [];
    
      @override
      void initState() {
        super.initState();
        loadData();
      }
    
      loadData() async {
        NewsService.getNews().then((value) {
          print(value);
          setState(() {
            articles = value ?? [];
          });
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('Haberler'),
            centerTitle: true,
          ),
          body: Center(
              child: articles.isEmpty
                  ? Text("loading or something")
                  : ListView.builder(
                      itemCount: articles.length,
                      itemBuilder: (context, index) {
                        return Card(
                          child: Column(
                            children: [
                              if (articles[index].urlToImage != null)
                                Image.network(articles[index].urlToImage!),
                              ListTile(
                                leading: Icon(Icons.arrow_drop_down_circle),
                                title: Text(articles[index].title ?? ""),
                                subtitle: Text(articles[index].author ?? ""),
                              ),
                              Padding(
                                padding: const EdgeInsets.all(16.0),
                                child: Text(
                                    'açıklama açıklama açıklamaaçıklama açıklamaaçıklama'),
                              ),
                              ButtonBar(
                                alignment: MainAxisAlignment.start,
                                children: [
                                  ElevatedButton(
                                      onPressed: () async {
                                        if (articles[index].url == null) {
                                          return;
                                        }
                                        await launchUrl(
                                            Uri.parse(articles[index].url!));
                                      },
                                      child: Text('Habere git'))
                                ],
                              )
                            ],
                          ),
                        );
                      })),
        );
      }
    }
    

    You need to use Uri to launch

    onPressed: () async {
      if (articles[index].url == null) {
        return;
      }
      await launchUrl(
          Uri.parse(articles[index].url!));
    },
    

    Also make sure to set up the configurationsection

    More about url_launcher