如何使用 Navigator 将数据(base64 - 字符串)传递到 Flutter 中的上一个屏幕?

时间:2021-03-26 11:35:04

标签: flutter dart

我有一个应用程序,我想在其中拍照并将其发送到服务器。为此,我使用术语 base46。当我按下按钮时,我会转到相机打开的页面,在那里我拍照并将其转换为 base64 格式。但问题是我无法将这个词返回到上一页。这是我使用相机转到页面的代码部分:

Expanded(
    child: ButtonTheme(
        alignedDropdown: true,
        child: new RaisedButton.icon(
        label: Text('Add image'),
        onPressed: () {Navigator.push(
            context,
            MaterialPageRoute(
                builder: (context) => image.PicturePreview(camera)),
            );
        },
        icon : Icon(Icons.camera_alt),
        )
    ),
),

这里是转换术语的页面(_imageB64)。我将不胜感激)

    import 'dart:async';
    import 'dart:io';
    import 'dart:convert';
    import 'package:camera/camera.dart';
    import 'package:flutter/material.dart';


    class PicturePreview extends StatefulWidget {
      final CameraDescription camera;
      const PicturePreview(this.camera, {Key key}) : super(key: key);

      @override
      _PicturePreviewState createState() => _PicturePreviewState();
    }
    class _PicturePreviewState extends State<PicturePreview> {

      CameraController _controller;
      Future<void> _initializeControllerFuture;

      @override
      String _imageB64;
      File _image;
      void initState() {
        super.initState();
        // To display the current output from the Camera,
        // create a CameraController.
        _controller = CameraController(
          // Get a specific camera from the list of available cameras.
          widget.camera,
          // Define the resolution to use.
          ResolutionPreset.medium,
        );

        // Next, initialize the controller. This returns a Future.
        _initializeControllerFuture = _controller.initialize();
      }

      @override
      void dispose() {
        // Dispose of the controller when the widget is disposed.
        _controller.dispose();
        super.dispose();
      }

      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: FutureBuilder<void>(
            future: _initializeControllerFuture,
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.done) {
                // If the Future is complete, display the preview.
                return CameraPreview(_controller);
              } else {
                // Otherwise, display a loading indicator.
                return Center(child: CircularProgressIndicator());
              }
            },
          ),
          floatingActionButton: FloatingActionButton(
            child: Icon(Icons.camera_alt),
            // Provide an onPressed callback.
            onPressed: () async {
              // Take the Picture in a try / catch block. If anything goes wrong,
              // catch the error.
              try {
                // Ensure that the camera is initialized.
                await _initializeControllerFuture;

                // Attempt to take a picture and get the file `image`
                // where it was saved.
                final image = await _controller.takePicture();
                _image = File(image.path);
                List<int> imageBytes = _image.readAsBytesSync();
                _imageB64 = base64Encode(imageBytes);
                 
              } catch (e) {
                // If an error occurs, log the error to the console.
                print(e);
              }
            },
          ),
        );
      }
    }

1 个答案:

答案 0 :(得分:2)

假设您想关闭相机页面并返回上一页返回结果,您可以使用Navigator.of(context).pop(_imageB64)返回Base64编码的字符串。

首先将调用代码改为

onPressed: () async {
  String imageB64 = await Navigator.push(
    context,
    MaterialPageRoute(builder: (context) => image.PicturePreview(camera)),
  );

  // Now you can do whatever you want with the Base64-encoded image
},

然后,在您的相机屏幕中,您可以在关闭屏幕时返回图像:

onPressed: () async {
  // Take the Picture in a try / catch block. If anything goes wrong,
  // catch the error.
  try {
    // Ensure that the camera is initialized.
    await _initializeControllerFuture;

    // Attempt to take a picture and get the file `image`
    // where it was saved.
    final image = await _controller.takePicture();
    _image = File(image.path);
    List<int> imageBytes = _image.readAsBytesSync();
    _imageB64 = base64Encode(imageBytes);

     // Close the page and return the result
     Navigator.of(context).pop(_imageB64);
  } catch (e) {
    // If an error occurs, log the error to the console.
    print(e);
  }
},
相关问题