Home > Back-end >  How can I change a background screen with a photo fetched from api in flutter?
How can I change a background screen with a photo fetched from api in flutter?

Time:04-15

I'm fetching images from https://pixabay.com/api/docs/ this web-page. I'm trying to save that image with onTap() {} with Shared Preferences package and set as background on previous page. I tried to make Shared preferences class seperate but it was showing errors. So pref.setString() method I did in ontap() {} and pref.getString() in my Center() widget with ternary operator to show that if image url is empty, write text, if it contains image url, show image. I tried to put it into setState() {} method but there are all red squiggles. How can I achieve this? Thank you very much in advance.

Here is my code:

this is the page I'm trying to set background image:

import 'package:abcde/authentication_screen/pages/photos_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class AfterAuth extends StatefulWidget {
  AfterAuth({Key? key}) : super(key: key);
  static const String pathId = 'Welcome Page';

  @override
  State<AfterAuth> createState() => _AfterAuthState();
}

class _AfterAuthState extends State<AfterAuth> {
  String welcomeScreen = 'Welcome to the club';

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    //final prefs = await SharedPreferences.getInstance();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Welcome'),
      ),
      drawer: Drawer(
        backgroundColor: Colors.white,
        child: ListView(
          padding: EdgeInsets.zero,
          children: [
            const DrawerHeader(
              decoration: BoxDecoration(
                color: Colors.lightBlueAccent,
              ),
              child: Text('Welcome'),
            ),
            ListTile(
              title: const Text(
                'Bonjour',
              ),
              onTap: () {
                setState(() {
                  welcomeScreen = 'Bonjour';
                });
                Navigator.pop(context);
              },
            ),
            ListTile(
              title: const Text('Hello'),
              onTap: () {
                setState(() {
                  welcomeScreen = 'Hello';
                });
                Navigator.pop(context);
              },
            ),
            ListTile(
              title: const Text('Guten Tag'),
              onTap: () {
                setState(() {
                  welcomeScreen = 'Guten Tag';
                });
                Navigator.pop(context);
              },
            ),
            ListTile(
              title: const Text('Au Revoir'),
              onTap: () {
                setState(() {
                  welcomeScreen = 'Au Revoir';
                });
                Navigator.pop(context);
              },
            ),
            ListTile(
              title: const Text('Chao Bambino'),
              onTap: () {
                setState(() {
                  welcomeScreen = 'Chao Bambino';
                });
                Navigator.pop(context);
              },
            ),
          ],
        ),
      ),
      body: Center(
        child: address == ''
            ? Text(welcomeScreen)
            : Image(
                image: NetworkImage(address),
              ),
      ),
      floatingActionButton: FloatingActionButton(
        backgroundColor: Colors.lightBlue,
        onPressed: () {
          Navigator.pushNamed(context, PhotosPage.pathId);
        },
        child: const Icon(
          Icons.add,
          color: Colors.white,
        ),
      ),
    );
  }

  String address = '';

  internalMemory() async {
    final prefs = await SharedPreferences.getInstance();
    address = prefs.getString('urlAddress')!;
/*    if(address!.isNotEmpty) {
      isAddressEmpty = false;
    }*/
    return address;
  }
}

this is the page where I fetch images from api and trying to save with Shared Preferences. actually not sure if it saves and not sure how to check it:

import 'package:flutter/material.dart';

import '../../services/photos_service.dart';
import 'package:shared_preferences/shared_preferences.dart';


class PhotosPage extends StatefulWidget {
  const PhotosPage({Key? key}) : super(key: key);
  static const String pathId = 'Photos page';

  @override
  State<PhotosPage> createState() => _PhotosPageState();
}

class _PhotosPageState extends State<PhotosPage> {
  PhotosService photosService = PhotosService();
  @override
  void initState() {
    super.initState();
    photosService.getPhotos();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Photos'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(children: [
          _getProductTypeList(),
        ]),
      ),
    );
  }

  Widget _buildListItem(
      BuildContext context, AsyncSnapshot<dynamic> snapshot, int index) {
    final photoItem = snapshot.data[index].previewURL;
    print('photoItem is $photoItem');
    return photoCard(context, photoItem);
  }

  Widget _buildList(BuildContext context, AsyncSnapshot<dynamic> snapshot) {
    var values = snapshot.data;
    return ListView.builder(
      itemCount: snapshot.hasData ? snapshot.data.length : 0,
      itemBuilder: (context, index) {
        return _buildListItem(context, snapshot, index);
      },
    );
  }

  Widget _getProductTypeList() {
    return Expanded(
      child: FutureBuilder(
        future: photosService.getPhotos(),
        builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(
              child: LinearProgressIndicator(),
            );
          }
          return _buildList(context, snapshot);
        },
      ),
    );
  }
}

Widget photoCard(BuildContext context, String url) {
  return GestureDetector(
    onTap: () async {
      final prefs = await SharedPreferences.getInstance();
      await prefs.setString('urlAddress', url);
      const snackBar =
      SnackBar(content: Text('You saved image'));
      ScaffoldMessenger.of(context).showSnackBar(snackBar);
    },
    child: Card(
      child: Image(
        image: NetworkImage(url),
      ),
    ),
  );
}

this is my service/model

import 'dart:convert';

import 'package:http/http.dart';

const apiKey = '26711456-bde74f403cb42e77029bc1678';
const appUrl = 'https://pixabay.com/api/';

class PhotosService {
  Future getData(String url) async {
    print('Calling url: $url');
    final response = await get(Uri.parse(url));
    if (response.statusCode == 200) {
      return response.body;
    } else {
      print(response.statusCode);
    }
  }
String? query;
  List<PhotosModel> dataList = [];
  Future<List<PhotosModel>> getPhotos() async {
    final photosData = await getData('$appUrl?key=$apiKey&q=$query');
    var data = json.decode(photosData);
    var items = data["hits"];
    items.forEach((element) {
      dataList.add(PhotosModel.fromJson(element));
    });

    print('this is photos data: $photosData');
    return dataList;
  }
}

class PhotosModel {
  String previewURL;

  PhotosModel({required this.previewURL});

  factory PhotosModel.fromJson(Map<dynamic, dynamic> json) =>
      _commentFromJson(json);

  Map<dynamic, dynamic> toJson() => photosModelToJson(this);
}

PhotosModel _commentFromJson(Map<dynamic, dynamic> json) {
  return PhotosModel(
    previewURL: json['previewURL'],
  );
}

Map<dynamic, dynamic> photosModelToJson(PhotosModel instance) =>
    <dynamic, dynamic>{
      'previewURL': instance.previewURL,
    };

CodePudding user response:

Call your function on initState to set the background on restart the app.

  @override
  void initState() {
  // TODO: implement initState
   super.initState();
   internalMemory();
   //final prefs = await SharedPreferences.getInstance();
 }

add setstate to your internalMemory() function to set background

  internalMemory() async {
   final prefs = await SharedPreferences.getInstance();
   address = await prefs.getString('urlAddress')!;
   setState((){});
  }

also, add the function below to set the background when you navigate back.

 floatingActionButton: FloatingActionButton(
    backgroundColor: Colors.lightBlue,
    onPressed: () async {
     await Navigator.pushNamed(context, PhotosPage.pathId);
      internalMemory();
    },
    child: const Icon(
      Icons.add,
      color: Colors.white,
    ),
  ),
  • Related