如何使用从 api 中获取的照片更改背景屏幕?

How can I change a background screen with a photo fetched from api in flutter?

我正在从 https://pixabay.com/api/docs/ 此网页中获取图像。 我正在尝试使用带有共享首选项包的 onTap() {} 保存该图像,并在上一页上设置为背景。我试图将共享首选项 class 分开,但它显示错误。所以 pref.setString() 我在我的 Center() 小部件中使用三元运算符在 ontap() {} 和 pref.getString() 中执行的方法表明如果图像 url 为空,则写入文本,如果它包含图像 url,则显示图像。我试图将其放入 setState() {} 方法中,但全是红色波浪线。我怎样才能做到这一点? 非常感谢您。

这是我的代码:

这是我要设置背景图片的页面:

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;
  }
}

这是我从 api 获取图像并尝试使用共享首选项保存的页面。实际上不确定它是否保存并且不确定如何检查它:

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),
      ),
    ),
  );
}

这是我的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,
    };

在 initState 上调用您的函数以设置重启应用程序的背景。

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

将 setstate 添加到您的 internalMemory() 函数以设置背景

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

另外,添加下面的功能设置返回时的背景。

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